<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item prop="wkorderNo">
        <el-input v-model="queryParams.wkorderNo" placeholder="请输入工单编号" clearable size="small" @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
<el-button type="primary" plain icon="el-icon-plus" size="small" @click="handleAdd" v-hasPermi="['iot:workorders:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
<el-button type="success" plain icon="el-icon-edit" size="small" :disabled="single || isStatusCompletedOrCancelled" @click="handleUpdate" v-hasPermi="['iot:workorders:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
<el-button type="danger" plain icon="el-icon-delete" size="small" :disabled="multiple || isStatusPendingOrInProgress" @click="handleDelete" v-hasPermi="['iot:workorders:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
<el-button type="warning" :plain="selectedRows.length===0" size="mini" :disabled="selectedRows.length===0" @click="handleCommon(selectedRows,'3')">
          <i class="el-icon-close" style="font-size:1.3em;margin-right:6px;"/>取消</el-button>
<el-button type="primary" :plain="selectedRows.length===0" size="mini" :disabled="selectedRows.length===0" @click="handleCommon(selectedRows,'1')">
          <i class="el-icon-check" style="font-size:1.3em;margin-right:6px;"/>完成</el-button>
<el-button type="danger" :plain="selectedRows.length===0" size="mini" :disabled="selectedRows.length===0" @click="handleCommon(selectedRows,'2')">
          <i class="el-icon-turn-off" style="font-size:1.3em;margin-right:6px;"/>关闭</el-button></el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"/></el-row>
    <div class="table-scroll-container">
    <el-table v-loading="loading" :data="workordersList" @selection-change="handleSelectionChange" style="width:100%;min-width:1729px">
        <el-table-column type="selection" width="45" align="center" />
        <el-table-column label="ID" align="center" prop="id" width="50" />
        <el-table-column label="工单编号" align="center" prop="wkorderNo" width="150" />
        <el-table-column label="问题描述" align="center" prop="description" width="400" show-overflow-tooltip />
        <el-table-column label="工单类型" prop="wkorderType" align="center" width="100">
          <template slot-scope="scope"><dict-tag :options="dict.type.workorder_type" :value="scope.row.wkorderType"/></template>
        </el-table-column>
        <el-table-column label="优先级" prop="priority" align="center" width="100">
          <template slot-scope="scope"><dict-tag :options="dict.type.wkorder_priority" :value="scope.row.priority"/></template>
        </el-table-column>
        <el-table-column label="工单状态" prop="status" align="center" width="100">
          <template slot-scope="scope"><dict-tag :options="dict.type.order_st" :value="scope.row.status"/></template>
        </el-table-column>
        <el-table-column label="维保人员" prop="assigneeId" align="center" width="100">1045
          <template slot-scope="scope"><span class="staff-name-badge">{{ getStaffName(scope.row.assigneeId) }}</span></template>
        </el-table-column>
        <el-table-column label="取消时间" align="center" prop="firstResponseTime" width="168">
          <template slot-scope="scope">{{scope.row.firstResponseTime}}</template>
        </el-table-column>
        <el-table-column label="解决时间" align="center" prop="resolvedAt" width="168">
          <template slot-scope="scope">{{scope.row.resolvedAt}}</template>
        </el-table-column>
        <el-table-column label="关闭时间" align="center" prop="closedAt" width="168">
          <template slot-scope="scope">{{scope.row.closedAt}}</template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" :disabled="isEditDisabled(scope.row.status)" @click="handleUpdate(scope.row)" v-hasPermi="['iot:workorders:edit']">修改</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" :disabled="isDeleteDisabled(scope.row.status)" @click="handleDelete(scope.row)" v-hasPermi="['iot:workorders:remove']">删除</el-button>
          </template>
        </el-table-column></el-table><div class="width-guarantee"/></div>
<pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" :page-sizes="pageSizes" @pagination="getList"/>
    <el-dialog :title="title" :visible.sync="open" width="1024px" append-to-body>
      <div class="scrollable-content">
      <el-form ref="form" :model="form" :rules="rules" label-width="96px">
        <el-form-item label="工单编号" prop="wkorderNo">
          <el-input v-model="form.wkorderNo" placeholder="请输入工单编号" />
        </el-form-item>
        <el-form-item label="工单类型" prop="wkorderType">
          <el-select v-model="form.wkorderType" placeholder="请选择工单类型" filterable style="width:100%">
            <el-option v-for="dict in dict.type.workorder_type" :key="dict.value" :label="dict.label" :value="dict.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="问题描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入问题描述" />
        </el-form-item>
        <el-form-item label="图片/视频">
          <fileUpload v-model="form.detailfile"/>
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-select v-model="form.priority" placeholder="请选择优先级" filterable style="width:100%">
            <el-option v-for="dict in dict.type.wkorder_priority" :key="dict.value" :label="dict.label" :value="dict.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="维保人员" prop="assigneeId">
          <el-select v-model="form.assigneeId" placeholder="请选择维保人员" filterable style="width:100%" @change="handleStaffnameChange">
            <el-option v-for="item in staffnameOptions" :key="item.id" :label="item.staffname" :value="item.id"/>
          </el-select>
        </el-form-item>
      </el-form></div>
<div slot="footer" class="dialog-footer"><el-button type="primary" @click="submitForm">确 定</el-button><el-button @click="cancel">取 消</el-button></div>
    </el-dialog></div></template>
<script>
import { listWorkorders, getWorkorders, delWorkorders, addWorkorders, updateWorkorders, updWorkorders } from "@/api/iot/workorders";
import { listStaff } from "@/api/iot/staff";
export default {
  dicts:['wkorder_priority','workorder_type','order_st'],
  name: "Workorders",
  data() {
    return {
      selectedRows: [],
      staffnameOptionss: [],
      staffnameOptions: [],
      pageSizes: [10,20,30,50],
      // 遮罩层
      loading: true,
      ids: [],
      assigneeIds: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 工单表格数据
      workordersList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        adminId: null,
        customerId: null,
        projectId: null,
        wkorderNo: null,
        title: null,
        description: null,
        detailfile: null,
        wkorderType: null,
        priority: null,
        status: null,
        creatorId: null,
        assigneeId: null,
        departmentId: null,
        firstResponseTime: null,
        resolvedAt: null,
        workStatus: null,
        ids: null,
        assigneeIds: null,
        closedAt: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        assigneeId: [{ required: true, message: "维保人员不能为空", trigger: "blur" }],
      }
    };
  },
  computed: {
    // 计算属性：检查选中的行中是否有状态为0或1的（用于禁用删除按钮）
    isStatusPendingOrInProgress() {
      return this.selectedRows.some(row => row.status === '0' || row.status === '1');
    },
    // 计算属性：检查选中的行中是否有状态为2或3的（用于禁用修改按钮）
    isStatusCompletedOrCancelled() {
      return this.selectedRows.some(row => row.status === '2' || row.status === '3');
    }
  },
  created() {
    this.getList();
    this.updStaffnames();
  },
  methods: {
    // 判断修改按钮是否禁用
    isEditDisabled(status) {
      // 状态为2或3时禁用修改按钮
      return status === '2' || status === '3';
    },
    // 判断删除按钮是否禁用
    isDeleteDisabled(status) {
      // 状态为0或1时禁用删除按钮
      return status === '0' || status === '1';
    },
    getStaffName(assigneeId) {
      const staff = this.staffnameOptionss.find(item => item.id === assigneeId);
      return staff ? staff.staffname : '-';
    },
    updStaffnames() {
      listStaff().then(response => {
        var resList = response.rows;
        if (response && resList) {
          this.staffnameOptions = resList.map(item => ({
            id: item.id,
            staffname: item.staffName,
          }));
          this.staffnameOptionss = this.staffnameOptions;
          console.log("updStaffnames:", this.staffnameOptions);
        } else {
          console.error('Invalid response format:', response);
        }
      }).catch(error => {
        console.error('Error fetching staff names:', error);
      });
    },
    async fetchStaffnames() {
      try {
        this.queryParams.workStatus = '0';
        const response = await listStaff(this.queryParams);
        var resList=response.rows;
        if (response && resList) {
          this.staffnameOptions = resList.map(item => ({
            id: item.id,  // 用于存储的项目 ID
            staffname: item.staffName,  // 用于展示的项目名称
          }));
          console.log("2", this.staffnameOptions);
        } else {
          console.error('Invalid response format:', response);
        }
      } catch (error) {
        console.error('Error fetching project names:', error);
      }
    },
    handleStaffnameChange(selectedId) {
      const selectedOption = this.staffnameOptions.find(option => option.id === selectedId);
      if (selectedOption) {
        this.form.assigneeId = selectedOption.id;
      } else {
        console.error('No matching data found for value:', value);
      }
    },
    getList() {
      this.loading = true;
      listWorkorders(this.queryParams).then(response => {
        this.workordersList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        id: null,
        adminId: null,
        customerId: null,
        projectId: null,
        wkorderNo: null,
        title: null,
        description: null,
        detailfile: null,
        wkorderType: null,
        priority: null,
        status: "0",
        creatorId: null,
        assigneeId: null,
        departmentId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        firstResponseTime: null,
        resolvedAt: null,
        ids: null,
        assigneeIds: null,
        closedAt: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.assigneeIds = selection.map(item => item.assigneeId)
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
      this.selectedRows = selection;
      this.workordersList.forEach(row => {
        row.checked = selection.some(item => item.id === row.id);
      });
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.fetchStaffnames();
      this.open = true;
      this.title = "新增";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getWorkorders(id).then(response => {
        this.form = response.data;
        this.updStaffnames();
        this.open = true;
        this.title = "修改";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateWorkorders(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            const assigneeId = this.form.assigneeId;
            this.form.assigneeIds = assigneeId ? [assigneeId] : [];
            addWorkorders(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除ID为"' + ids + '"的数据项？').then(function() {
        return delWorkorders(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleCommon(row, status) {
      const ids = row.id || this.ids;
      const assigneeIds = row.assigneeId || this.assigneeIds;
      let itemm = '';
      this.form.ids = ids;
      this.form.assigneeIds = assigneeIds;
      this.form.status = status;
      console.log('handleCommon:', this.form);
      if (status == '3') {
        itemm = '取消';
      } else if (status == '1') {
        itemm = '完成';
      } else if (status == '2') {
        itemm = '关闭';
      }
      this.$modal.confirm(`是否确认【${itemm}】ID为"${ids}"的数据项？`)
        .then(() => updWorkorders(this.form))
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("操作成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('iot/workorders/export', {
        ...this.queryParams
      }, `workorders_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped>
.table-scroll-container {
  width: 100%;
  overflow-x: auto !important;
  overflow-y: hidden;
  border: 1px solid #ebeef5;
  background: #fff;
  position: relative;
}
.table-scroll-container::-webkit-scrollbar {
  height: 12px !important;
  background: #f0f0f0 !important;
}
.table-scroll-container::-webkit-scrollbar-thumb {
  background: #c1c1c1 !important;
  border-radius: 6px !important;
}
.table-scroll-container ::v-deep .el-table {
  min-width: 1729px !important;
  width: auto !important;
}
.width-guarantee {
  width: 1729px;
  height: 1px;
  visibility: hidden;
}
.scrollable-content {
  max-height: 80vh;   /* 或固定像素值如 600px */
  overflow-y: scroll;  /* 改为scroll，始终显示滚动条 */
  padding-right: 10px; /* 避免滚动条遮挡内容 */
}
.scrollable-content::-webkit-scrollbar {
  width: 8px; /* 滚动条宽度 */
}
.scrollable-content::-webkit-scrollbar-track {
  background: #f1f1f1; /* 滚动条轨道颜色 */
  border-radius: 4px;
}
.scrollable-content::-webkit-scrollbar-thumb {
  background: #c0c0c0; /* 滚动条滑块颜色 */
  border-radius: 4px;
}
.scrollable-content::-webkit-scrollbar-thumb:hover {
  background: #a0a0a0; /* 滚动条滑块悬停颜色 */
}
.staff-name-badge {
  background-color: #f0f9ff;  /* 浅蓝色背景 */
  color: #1890ff;            /* 蓝色文字 */
  padding: 4px 8px;
  border-radius: 4px;
  border: 1px solid #d1e9ff;
  font-size: 12px;
  display: inline-block;
}
</style>
